<template>
  <page-view class="address">
    <page-header title="收货地址列表" :show-back="true"></page-header>
    <div class="content-box">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
      >
        <template #default>
          <div class="default-btn">
            <van-button round type="primary" @click="addChoose"
              >添加为当前收货地址</van-button
            >
            <van-button round type="primary" @click="addDefault"
              >添加为默认收货地址</van-button
            >
          </div>
        </template>
      </van-address-list>
    </div>
  </page-view>
</template>

<script setup>
import { useRouter } from "vue-router";
import { Toast } from "vant";
import { ref, reactive } from "vue";
import { useStore } from "vuex";
import Api from "../utils/api";
const router = useRouter();
const store = useStore();
let list = reactive([]);
let chosenAddressId = ref(1);

// 获取用户地址
const getAddress = async () => {
  if (store.state.addressInfo === null) {
    let results = await Api.addressInfo.findByUid();
    store.commit("setAddressInfo", results);
    results.forEach((item) => {
      list.push(item);
    });
  } else {
    store.state.addressInfo.forEach((item) => {
      list.push(item);
    });
  }
  let info = list.filter((item) => item.isDefault == 1);
  if (info.length != 0) {
    chosenAddressId.value = info[0].id;
  } else {
    chosenAddressId.value = list[0].id;
  }

  //根据组件的属性去做适配
  list.forEach((item) => {
    item.name = item.person_name;
    item.tel = item.phone;
  });
};
getAddress();

const onAdd = () => {
  router.push({ name: "AddAddress" });
};
const onEdit = (item, index) => {
  console.log(item);
  console.log(index);
  router.push({
    name: "EditAddress",
    query: {
      id: item.id,
    },
  });
};

const addChoose = () => {
  let choose = list.filter((item) => item.id == chosenAddressId.value);
  store.commit("setCurrentAddress", choose[0]);
  Toast.success({
    message: "收货地址选择成功",
    duration: 1000,
    onClose: () => {
      router.back();
    },
  });
};
const addDefault = async () => {
  await Api.addressInfo.setDefault(chosenAddressId.value);
  let results = await Api.addressInfo.findByUid();
  store.commit("setAddressInfo", results);
  list.forEach((item) => {
    item.isDefault = 0;
    if (item.id == chosenAddressId.value) item.isDefault = 1;
  });
};
</script>

<style lang="scss" scoped>
.address {
  .content-box {
    flex: 1;
    overflow: auto;
    .default-btn {
      position: fixed;
      bottom: 50px;
      left: 0;
      width: 100vw;
      box-sizing: border-box;
      padding: 0px 15px;
      button {
        width: 100%;
        margin-top: 5px;
      }
    }
  }
}
</style>